import 'package:environmental_les_app/common/style/colours.dart';
import 'package:environmental_les_app/common/widgets/button_public_rect.dart';
import 'package:flutter/material.dart';

import 'bottom_pop_window_bg.dart';

class BottomScreenDialog extends StatefulWidget {
  final List<Map<String, dynamic>> filterData;
  // 是否多选，默认 false（单选）
  final bool multiSelect;
  // 初始选中项，key -> list of values
  final Map<String, List<String>>? initialSelected;

  const BottomScreenDialog({
    super.key,
    required this.filterData,
    this.multiSelect = false,
    this.initialSelected,
  });

  @override
  State<BottomScreenDialog> createState() => _BottomScreenDialogState();
}

class _BottomScreenDialogState extends State<BottomScreenDialog> {
  // 筛选数据
  List<Map<String, dynamic>> _filterData = [];

  // 当前选中值 (prop -> Set of values)
  final Map<String, Set<String>> _selected = {};

  @override
  void initState() {
    super.initState();
    _filterData = widget.filterData;
    // 初始化为空集合
    for (final item in _filterData) {
      final prop = item['prop'] as String;
      final set = <String>{};
      // 应用初始值（如果提供）
      if (widget.initialSelected != null &&
          widget.initialSelected![prop] != null) {
        set.addAll(widget.initialSelected![prop]!);
      }
      _selected[prop] = set;
    }
  }

  @override
  Widget build(BuildContext context) {
    return BottomPopWindowBg(
      title: "筛选",
      children: [
        // filter sections
        for (final section in _filterData) ...[
          Align(
            alignment: Alignment.centerLeft,
            child: Text(section['title'] as String,
                style: const TextStyle(
                    fontSize: 16,
                    color: Colours.text254,
                    fontWeight: FontWeight.w500)),
          ),
          const SizedBox(height: 12),
          Wrap(
            spacing: 12,
            runSpacing: 12,
            children: [
              for (final opt in (section['filter'] as List))
                _buildOption(section['prop'] as String, opt,
                    (section['multiSelect'] as bool?) ?? widget.multiSelect),
            ],
          ),
          const SizedBox(height: 18),
        ],

        const SizedBox(height: 10),

        // bottom actions
        Row(
          children: [
            Expanded(
              flex: 1,
              child: ButtonPublicRect(
                text: "重置",
                type: ButtonPublicType.outline,
                onPressed: _onReset,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              flex: 3,
              child: ButtonPublicRect(
                minWidth: double.infinity,
                text: "确认",
                onPressed: _onConfirm,
              ),
            ),
          ],
        ),
        const SizedBox(height: 6),
      ],
    );
  }

  Widget _buildOption(String prop, Map opt, bool multi) {
    final name = opt['name'] as String;
    final value = opt['value'] as String;
    final selected = _selected[prop]?.contains(value) ?? false;

    return GestureDetector(
      onTap: () {
        setState(() {
          final set = _selected[prop]!;
          if (selected) {
            set.remove(value);
          } else {
            if (multi) {
              set.add(value);
            } else {
              // 单选行为：清空后添加
              set.clear();
              set.add(value);
            }
          }
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
        decoration: BoxDecoration(
          color: selected ? Colours.bgECF5FF : Colours.bgF7F8FA,
          borderRadius: BorderRadius.circular(4),
          border: selected ? Border.all(color: Colours.line629EFF) : null,
        ),
        child: Text(name,
            style:
                TextStyle(color: selected ? Colours.appMain : Colours.text254)),
      ),
    );
  }

  void _onReset() {
    setState(() {
      for (final key in _selected.keys) {
        _selected[key]!.clear();
      }
    });
  }

  void _onConfirm() {
    // 返回选中结果，格式根据 multiSelect 不同而不同
    final Map<String, dynamic> result = {};
    for (final entry in _selected.entries) {
      if (widget.multiSelect) {
        result[entry.key] = entry.value.toList();
      } else {
        result[entry.key] = entry.value.isEmpty ? null : entry.value.first;
      }
    }
    Navigator.of(context).pop(result);
  }
}
